export default {
    init(callback) {
        const getData = (res)=>{
            const {initiatorType,name,duration,} = res
            return {
                initiatorType, name, duration,
                redirect: res.redirectEnd - res.redirectStart, // 重定向
                dns: res.domainLookupEnd - res.domainLookupStart, // DNS 查找
                connect: res.connectEnd - res.connectStart, // TCP 握手
                network: res.connectEnd - res.navigationStart, // 网络总耗时
                send: res.requestStart - res.requestStart, // 发送到接收时间
                receive: res.responseEnd - res.responseStart, // 接收数据耗时
                request: res.responseEnd - res.requestStart, // 请求页面总耗时
                ttfb: res.responseStart - res.navigationStart, // 首字节时间
            }
        } 
        if(window.PerformanceObserver){
            // 需要放在 html 最上面
            let observer = new window.PerformanceObserver(list=>{
                try {
                    const entries = list.getEntries()
                    console.log(entries)
                } catch (error) {
                    
                }
            })
            observer.observe({entryTypes:['resource']})
        }else{
            // onload 之后获得所有
            onload(() => {
                const entries = performance.getEntries('resource')
                let performanceData =  entries.map(res => getData(res))
                callback(performanceData)
            })
        }
       
    }
}

function onload(cb) {
    if (document.readyState === 'complete') {
        cb()
        return
    }
    window.addEventListener('load', () => {
        cb()
    })
}